package com.ncu.cloundeoffice.controller;

import com.ncu.cloundeoffice.mapper.TRoleMapper;
import com.ncu.cloundeoffice.pojo.ResponseResult;
import com.ncu.cloundeoffice.pojo.TMenu;
import com.ncu.cloundeoffice.pojo.TRole;
import com.ncu.cloundeoffice.service.TMenuRoleService;
import com.ncu.cloundeoffice.service.TMenuService;
import com.ncu.cloundeoffice.service.TRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/basic/role")
public class TRoleController {

    @Autowired
    private TRoleService tRoleService;

    @Autowired
    private TMenuService tMenuService;

    @Autowired
    private TMenuRoleService tMenuRoleService;

    /**
     * 查询所有的角色
     * @return
     */
    @GetMapping("/")
    public List<TRole>  getAllTRole(){
        return tRoleService.getAllTRole();
    }


    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResponseResult deleteTRole(@PathVariable("id") int id){
        int count = tRoleService.deleteTRole(id);
        if(count == 1){
            return ResponseResult.success("删除成功");
        }else {
            return ResponseResult.error("删除失败");
        }
    }

    /**
     * 添加角色
     * @param tRole
     * @return
     */
    @PostMapping("/")
    public ResponseResult addTRole(@RequestBody TRole tRole){
        if(!tRole.getName().startsWith("ROLE_")){
            tRole.setName("ROLE_"+tRole.getName());
        }
        int count = tRoleService.addTRole(tRole);
        if(count == 1){
            return ResponseResult.success("添加成功");
        }else {
            return ResponseResult.error("添加失败");
        }
    }


    /**
     * 查询所有的菜单
     * @return
     */
    @GetMapping("/menus")
    public List<TMenu> getAllMenus(){
        return tMenuService.getAllMenus();
    }


    /**
     * 通过角色id查询菜单id
     * @param rid
     * @return
     */
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable int rid){
        return tMenuRoleService.getMidByRid(rid);
    }

    /**
     * 更新角色菜单
     * @param rid
     * @param mids
     * @return
     */
    @PutMapping("/")
    public ResponseResult updateMenuRoleByRidAndMid(@RequestParam("rid") int rid,
                                                    @RequestParam("mids") int[] mids){
        return tMenuRoleService.updateMenuRoleByRidAndMid(rid,mids);
    }
}
